Get sound to play with a button through a web server
import network
import socket
import machine
import threading
from time import sleep
ssid = 'EECS_Labs'
password = ''
#ssid = ''
#password = ''
# Define the pin connected to the LM4871 amplifier
signal_pin = machine.Pin(10, machine.Pin.OUT)
shutdown_pin = machine.Pin(9, machine.Pin.OUT)
# Create a PWM object
pwm = machine.PWM(signal_pin)
# Set initial state of the PWM signal
pwm.duty(0) # Turn off the sound
# Variable to track the state of the music
music_playing = False
def connect():
# Connect to WLAN
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
print('Waiting for connection...')
sleep(1)
ip = wlan.ifconfig()[0]
print(f'Connected on {ip}')
return ip
def open_socket(ip):
# Open a socket
address = (ip, 80)
connection = socket.socket()
connection.bind(address)
connection.listen(1)
return connection
def play_music():
# Add your music playing logic here
pwm.duty(300) # Set duty cycle for sound
pwm.freq(440) # Set frequency (440 Hz is an example)
def stop_music():
# Turn off the sound
pwm.duty(0)
def play_music_thread():
global music_playing
while music_playing:
play_music()
def serve(connection):
global music_playing
# Start a web server
while True:
client = connection.accept()[0]
request = client.recv(1024)
request = str(request)
try:
request = request.split()[1]
except IndexError:
pass
print('Received request:', request)
if request == '/togglemusic':
print('Toggling music...')
if music_playing:
# Stop playing music
music_playing = False
stop_music()
else:
# Start playing music in a separate thread
music_playing = True
threading.Thread(target=play_music_thread).start()
client.send("HTTP/1.1 200 OK\nContent-Length: {}\n\n{}".format(len(html_css_code), html_css_code))
client.close()
try:
# Set initial state of the shutdown pin
shutdown_pin.off() # Assuming high is off, adjust if necessary
ip = connect()
connection = open_socket(ip)
pwm.duty(0) # Turn off the sound
serve(connection)
except KeyboardInterrupt:
# Set the shutdown pin to high before resetting
shutdown_pin.on() # Assuming high is off, adjust if necessary
machine.reset()